<!--
 * @Description: 审批人员选择
 * @Author: wangwangwang
 * @Date: 2020-08-07 12:02:33
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-08-26 10:05:22
-->
<template>
  <el-dialog v-dialogDrag width="50%" :title="title || '选择人员'" :before-close="hanldeClose" :visible.sync="visible">
    <div class="form-container">
      <el-form :inline="true" :model="personTypeForm">
        <el-form-item label="选择类别">
          <el-select v-model="personTypeForm.type">
            <el-option v-show="type===2" label="组织" value="4"></el-option>
            <el-option label="角色" value="2"></el-option>
            <el-option v-show="type===2" label="岗位" value="3"></el-option>
            <el-option label="人员" value="1"></el-option>
            <el-option v-show="type===2" label="分管领导" value="5"></el-option>
            <el-option v-show="type===2" label="主管" value="6"></el-option>
            <el-option v-show="type===2" label="副主管" value="7"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="personTypeForm.type==='1'">
          <el-input v-model="personTypeForm.person" placeholder="搜索人员"></el-input>
        </el-form-item>
        <el-form-item v-show="personTypeForm.type==='1'">
          <el-button class="bottom_all" @click="searchSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="transfer-container">
      <el-row :gutter="10">
        <el-col :span="9">
          <p class="hanlde-title">未选:</p>
          <div v-loading='loading' class="hanlde-container">
            <el-tree v-show="personTypeForm.type==='1'" ref="tree" :check-strictly="strictly" check-on-click-node class="tree-line" :indent="0" :data="treeArry" show-checkbox node-key="id" highlight-current :props="defaultProps"></el-tree>
            <el-tree v-show="personTypeForm.type==='4'" ref="tree2" :check-strictly="true" check-on-click-node class="tree-line" :indent="0" :data="organizationList" show-checkbox node-key="id" highlight-current :props="defaultProps"></el-tree>
            <el-tree v-show="personTypeForm.type==='3'" ref="tree3" :check-strictly="true" check-on-click-node class="tree-line" :indent="0" show-checkbox node-key="id" highlight-current :props="defaultProps2" :load="loadNode" lazy></el-tree>
            <el-checkbox-group v-show="personTypeForm.type==='2'" v-model="selectRoles">
              <div v-for="item in rolesData" :key="item.id">
                <el-checkbox :label="item">{{item.name}}</el-checkbox>
              </div>
            </el-checkbox-group>
            <el-tree v-show="personTypeForm.type==='5'" ref="tree5" :check-strictly="true" check-on-click-node class="tree-line" :indent="0" :data="organizationList" show-checkbox node-key="id" highlight-current :props="defaultProps"></el-tree>
            <el-tree v-show="personTypeForm.type==='6'" ref="tree6" :check-strictly="true" check-on-click-node class="tree-line" :indent="0" :data="organizationList" show-checkbox node-key="id" highlight-current :props="defaultProps"></el-tree>
            <el-tree v-show="personTypeForm.type==='7'" ref="tree7" :check-strictly="true" check-on-click-node class="tree-line" :indent="0" :data="organizationList" show-checkbox node-key="id" highlight-current :props="defaultProps"></el-tree>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="handle-submit">
            <div>
              <el-button class="bottom_all" style="margin-left:0;" @click="setSelectedData">
                <i class="el-icon-arrow-right el-icon--right" />
              </el-button>
            </div>
            <div>
              <el-button class="bottom_all" style="margin-left:0;" @click="cancleSelectedData">
                <i class="el-icon-arrow-left el-icon--left"></i>
              </el-button>
            </div>
            <div>
              <el-button class="bottom_all_two" style="margin-left:0;" @click="clearSelectedData">清空已选</el-button>
            </div>
          </div>
        </el-col>
        <el-col :span="9">
          <p class="hanlde-title">已选:</p>
          <div class="hanlde-container">
            <el-checkbox-group v-model="choisedData">
              <div v-for="item in selectedData" :key="item.ids">
                <el-checkbox :label="item">{{item.name}}</el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </el-col>
      </el-row>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button class="bottom_all_two" @click="hanldeClose">取 消</el-button>
      <el-button class="bottom_all" @click="hanldeSure">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
// import { queryPage as orgQueryPage } from "@/api/basedata/organization";
// import { queryPage as userQueryPage } from "@/api/basedata/user";
import { getIdList } from '@/api/common';
import { formatTreeData } from "@/utils/utils";

export default {
  props: ["visible", 'choisedDatas', 'title', 'isPerson', 'strictly', 'type'],
  data() {
    return {
      personTypeForm: {
        type: "1",
      },
      treeArry: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      defaultProps2: {
        children: "children",
        label: "name",
        isLeaf: 'leaf'
      },
      selectedData: [],
      choisedData: [],
      selectRoles: [],
      rolesData: [],
      allData: [],
      userList: [],
      organizationList: [],
      loading: false,
    };
  },
  watch: {
    visible(value) {
      if (value) {
        if (this.choisedDatas ?.length) {
          this.selectedData = this.choisedDatas;
          const newData = this.choisedDatas.map(item => item.id);
          setTimeout(() => {
            this.$refs.tree.setCheckedKeys(newData);
          }, 100)
          return
        }
        this.selectedData = [];
        setTimeout(() => {
          this.$refs.tree.setCheckedKeys([]);
        }, 100)
      }
    },
  },
  methods: {
    loadNode(node, resolve) {
      if (node.level === 0) {
        console.log(this.organizationList);
        return resolve(this.organizationList);
      }
      if (node.data.type === 2) {
        const params = {
          sourceId: node.data.id,
          type: "organization_stations",
        }
        getIdList(params).then(res => {
          if (res.code === 1001) {
            if (res.data.targetIds.length) {
              const newData = this.positionData.filter(item => res.data.targetIds.some(items => items === item.id)).map(item => ({name: `${node.data.name}-${item.name}`, id: `${item.id}-${node.data.id}`, leaf: true, type: 6 }));
              if (node.data.children && node.data.children.length) {
                resolve([...node.data.children, ...newData])
                return
              }
              resolve(newData)
              return
            }
            if (node.data.children && node.data.children.length) {
              resolve(node.data.children);
              return
            }
            return resolve([]);
          }
        })
      }
      return resolve([]);
    },
    /**
     * @Description: 设置已选
     * @Param:
     * @Author: wangwangwang
     */
    setSelectedData() {
      if (this.personTypeForm.type === "1") {
        let selectPerson = this.$refs.tree.getCheckedNodes();
        if (this.isPerson) {
          selectPerson = selectPerson.filter(item => item.organizationId)
        }
        const copyData = selectPerson.map((item) => ({
          name: item.name,
          id: item.id,
          ids: item.id+1,
          type: item.organizationId ? 1 : 2,
        }));
        const concatData = [...copyData, ...this.selectedData];
        const hash = {};
        const newData = concatData.reduce((item, next) => {
          hash[next.id] ? "" : (hash[next.id] = true && item.push(next));
          return item;
        }, []);
        this.selectedData = newData;
      } else if (this.personTypeForm.type === "2") {
        const copyData = this.selectRoles.map((item) => ({
          name: item.name,
          id: item.id,
          ids: item.id+2,
          type: 3,
        }));
        const concatData = [...copyData, ...this.selectedData];
        const hash = {};
        const newData = concatData.reduce((item, next) => {
          hash[next.id] ? "" : (hash[next.id] = true && item.push(next));
          return item;
        }, []);
        this.selectedData = newData;
      } else if (this.personTypeForm.type === "3") {
        let selectPerson = this.$refs.tree3.getCheckedNodes();
        selectPerson = selectPerson.filter(item => item.type === 6)
        const copyData = selectPerson.map((item) => ({
          name: item.name,
          id: item.id.split('-')[0],
          pid: item.id.split('-')[1],
          ids: item.id+3,
          type: 6,
        }));
        const concatData = [...copyData, ...this.selectedData];
        const hash = {};
        const newData = concatData.reduce((item, next) => {
          hash[next.ids] ? "" : (hash[next.ids] = true && item.push(next));
          return item;
        }, []);
        this.selectedData = newData;
      } else if (this.personTypeForm.type === "4") {
        let selectPerson = this.$refs.tree2.getCheckedNodes();
        const copyData = selectPerson.map((item) => ({
          name: item.name,
          id: item.id,
          ids: item.id+4,
          type: 2,
        }));
        const concatData = [...copyData, ...this.selectedData];
        const hash = {};
        const newData = concatData.reduce((item, next) => {
          hash[next.id] ? "" : (hash[next.id] = true && item.push(next));
          return item;
        }, []);
        this.selectedData = newData;
      } else if (this.personTypeForm.type === "5" || this.personTypeForm.type === "6" || this.personTypeForm.type === "7") {
        let selectPerson = {};
        if (this.personTypeForm.type === "5") {
          selectPerson = this.$refs.tree5.getCheckedNodes();
        }
        if (this.personTypeForm.type === "6") {
          selectPerson = this.$refs.tree6.getCheckedNodes();
        }
        if (this.personTypeForm.type === "7") {
          selectPerson = this.$refs.tree7.getCheckedNodes();
        }
        const copyData = selectPerson.map((item) => ({
          name: `${item.name}-${['','','','','','分管领导', '主管', '副主管'][this.personTypeForm.type*1]}`,
          id: item.id,
          ids: `${item.id+this.personTypeForm.type}`,
          type: this.personTypeForm.type,
        }));
        const concatData = [...copyData, ...this.selectedData];
        const hash = {};
        const newData = concatData.reduce((item, next) => {
          hash[next.ids] ? "" : (hash[next.ids] = true && item.push(next));
          return item;
        }, []);
        this.selectedData = newData;
      }
    },
    /**
     * @Description: 取消已选
     * @Param:
     * @Author: wangwangwang
     */
    cancleSelectedData() {
      this.selectedData = this.selectedData.filter(
        (item) => !this.choisedData.some((ele) => ele.ids === item.ids)
      );
      this.choisedData = [];
    },
    /**
     * @Description: 清除已选
     * @Param:
     * @Author: wangwangwang
     */
    clearSelectedData() {
      this.choisedData = [];
      this.selectedData = [];
    },
    /**
     * @Description: 获取角色数据
     * @Param:
     * @Author: wangwangwang
     */
    initRoleData() {
      const { state } = this.$store;
      if (!state.approvePerson.rolesData) {
        this.$store.dispatch("approvePerson/getroles").then(res => {
          this.rolesData = res;
        });
        return
      }
      this.rolesData = state.approvePerson.rolesData;
    },
    /**
     * @Description: 获取所有岗位
     * @param {*}
     * @Author: wangwangwang
     */
    initPosition () {
      const { state } = this.$store;
      if (!state.approvePerson.positionData) {
        this.$store.dispatch("approvePerson/getposition").then(res => {
          this.positionData = res;
        });
        return
      }
      this.positionData = state.approvePerson.positionData;
    },
    /**
     * @Description: 获取所有组织和用户、格式化tree结构
     * @Param:
     * @Author: wangwangwang
     */
    initOrganization() {
      const { state } = this.$store;
      if (!state.approvePerson.orgList || !state.approvePerson.orgList) {
        const orgPromise = this.$store.dispatch("approvePerson/getorg");
        const userPromise = this.$store.dispatch("approvePerson/getuser");
        this.loading = true;
        Promise.all([orgPromise, userPromise]).then(([orgres, userres]) => {
          this.formatDataSource(orgres, userres);
        }).catch(e => console.log(e));
      } else {
        this.formatDataSource( state.approvePerson.orgList, state.approvePerson.userList)
      }
    },
    formatDataSource (orgList, userList) {
      orgList.forEach((v) => {
        v.type = 2
      })
      this.organizationList = formatTreeData(orgList, "id","parentId","children","parent_id");
      userList.forEach((v) => {
        v.type = 1
      })
      const newArry = userList.map((item) => ({
        ...item,
        parentId: item.organizationId,
      }));
      this.userList = userList;
      this.treeArry = formatTreeData(
        orgList.concat(newArry),
        "id",
        "parentId",
        "children",
        "parent_id"
      );
      this.allData = formatTreeData(
        orgList.concat(newArry),
        "id",
        "parentId",
        "children",
        "parent_id"
      );
      this.loading = false;
    },
    hanldeClose() {
      this.$emit("closeModel");
    },
    hanldeSure() {
      this.$emit("getPerson", this.selectedData);
    },
    /**
     * @Description: 人员搜索
     * @Param: 
     * @Author: wangwangwang
     */
    searchSubmit() {
      if (this.personTypeForm.person) {
        const newData = this.userList.filter(item => item.name.indexOf(this.personTypeForm.person) > -1);
        this.treeArry = newData;
        return
      }
      this.treeArry = this.allData;
    }
  },
  mounted() {
    this.initOrganization();
    this.initRoleData();
    this.initPosition();
  },
};
</script>
<style lang="scss" scoped>
.transfer-container {
  .hanlde-title {
    margin-bottom: 10px;
  }
  .hanlde-container {
    border-radius: 5px;
    border: 1px solid #dcdfe6;
    height: 500px;
    overflow: scroll;
    padding: 15px;
  }
}
.handle-submit {
  padding-top: 200px;
  text-align: center;
  div {
    margin: 20px 0px;
  }
}
</style>
